// 小程序开发api接口工具包，https://github.com/gooking/wxapi
const CONFIG = require('./doconfig.js')
const API_BASE_URL = 'http://localhost:8080'


const request = (url, needSubDomain, method, data) => {
  let _url = API_BASE_URL + (needSubDomain ? '/' + CONFIG.subDomain : '') + url
  return new Promise((resolve, reject) => {
    wx.request({
      url: _url,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success(request) {
        resolve(request.data)
      },
      fail(error) {
        reject(error)
      },
      complete(aaa) {
        // 加载完成
      }
    })
  })
}

/**
 * 小程序的promise没有finally方法，自己扩展下
 */
// Promise.prototype.finally = function (callback) {
//   var Promise = this.constructor;
//   return this.then(
//     function (value) {
//       Promise.resolve(callback()).then(
//         function () {
//           return value;
//         }
//       );
//     },
//     function (reason) {
//       Promise.resolve(callback()).then(
//         function () {
//           throw reason;
//         }
//       );
//     }
//   );
// }

module.exports = {
  request,
  queryActionList: (data) => {
    return request('/action/actionList', true, 'post', data)
  },
  queryAction: (data) => {
    return request('/action/getAction', true, 'get', data)
  },
  joinAction: (data) => {
    return request('/action/joinAction', true, 'get', data)
  },
  cancelAction: (data) => {
    return request('/action/cancelAction', true, 'get', data)
  },
  banners: (data) => {
    return request('/banner/list', true, 'get', data)
  },
  queryConfig: (data) => {
    return request('/config/get-value', true, 'get', data)
  },
  queryConfigBatch: (keys) => {
    return request('/config/values', true, 'get', { keys })
  },checkToken: (token) => {
    return request('/user/check-token', true, 'get', {
      token
    })
  }, login: (code) => {
    return request('/login', true, 'get', {
      code,
      type: 2
    })
  }, getUserInfo: (data) => {
    return request('/info', true, 'get', data)
  }, getPhoneNoInfo: (data) => {
    return request('/phone', true, 'get', data)
  }, commitAction: (data) => {
    return request('/addAction', true, 'post', data)
  }
}